package com.company.behavioral.iterator_pattern.concrete_iterator;

import com.company.behavioral.iterator_pattern.concrete_aggregate.ProductList;
import com.company.behavioral.iterator_pattern.iterator.AbstractIterator;

import java.util.List;

/**
 * 商品迭代器
 * @ClassName ProductIterator
 * @Author tiezheng.han
 * @Date 2020/9/4 16:22
 **/
public class ProductIterator implements AbstractIterator {

    /**
     * 获取集合对象
     */
    private List<Object> products;

    /**
     * 设置正向遍历游标的初始值
     */
    private int cursor1;

    /**
     * 设置逆向遍历游标的初始值
     */
    private int cursor2;

    public ProductIterator(ProductList list) {
        this.products = list.getObjects();
        this.cursor1 = 0;
        this.cursor2 = products.size() -1;
    }

    @Override
    public void next() {
        if (cursor1 < products.size()){
            cursor1++;
        }
    }

    @Override
    public boolean isLast() {
        return (cursor1 == products.size());
    }

    @Override
    public void previous() {
        if (cursor2 > -1){
            cursor2--;
        }
    }

    @Override
    public boolean isFirst() {
        return (cursor2 == -1);
    }

    @Override
    public Object getNextItem() {
        return products.get(cursor1);
    }

    @Override
    public Object getPreviousItem() {
        return products.get(cursor2);
    }
}
